package com.cy.src.myapplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by CY on 2016/9/19.
 */

public class ZipHelper {

    public static void main(String[] args) {
//        new ZipHelper().zip(new File("C:\\Users\\Administrator\\Desktop\\新建文件夹"), new File("C:\\Users\\Administrator\\Desktop\\新建文件夹.zip"));
        new ZipHelper().zip(new File("C:\\Users\\Administrator\\Desktop\\工作任务.rtf"), new File("C:\\Users\\Administrator\\Desktop\\工作任务.rtf.zip"));
    }

    public void zip(File inputFile, File outZipFile) {
        try {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outZipFile));
            if (inputFile.isDirectory()) {
                zipDir(inputFile, zos);
            } else {
                zipFile(inputFile, zos);
            }
            zos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void zipFile(File file, ZipOutputStream zos) throws IOException {

        FileInputStream fis = new FileInputStream(file);


        ZipEntry zipEntry = new ZipEntry(file.getName());
        zos.putNextEntry(zipEntry);

        int index;
        byte[] data = new byte[2048];

        while ((index = fis.read(data)) != -1) {
            zos.write(data, 0, index);
        }
        zos.flush();
        zos.closeEntry();
//        ZipOutputStream zos=new ZipOutputStream();

    }

    private void zipDir(File inputDir, ZipOutputStream zos) throws IOException {

        File[] files = inputDir.listFiles();

        if (files != null) {
            for (File file : files) {

                if (file.isDirectory()) {
                    zipDir(file, zos);
                } else {
                    zipFile(file, zos);
                }
            }
        }

    }
}
